package com.ljyh.forum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljyh.forum.dto.PostDTO;
import com.ljyh.forum.entity.Post;
import com.ljyh.forum.entity.User;
import com.ljyh.forum.mapper.PostMapper;
import com.ljyh.forum.service.PostService;
import com.ljyh.forum.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 帖子服务实现类
 */
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {

    @Autowired
    private UserService userService;

    @Override
    public Page<PostDTO> getPostsPage(int page, int size, Integer categoryId, String sort) {
        Page<Post> pageParam = new Page<>(page, size);
        QueryWrapper<Post> queryWrapper = new QueryWrapper<>();
        
        // 分类筛选
        if (categoryId != null) {
            queryWrapper.eq("category_id", categoryId);
        }
        
        // 排序方式
        if ("hot".equals(sort)) {
            // 热门排序：按点赞数+评论数综合排序
            queryWrapper.orderByDesc("like_count + comment_count");
        } else {
            // 默认按最新排序
            queryWrapper.orderByDesc("create_time");
        }
        
        Page<Post> postPage = this.page(pageParam, queryWrapper);
        
        // 转换为DTO并填充用户信息
        Page<PostDTO> dtoPage = new Page<>(postPage.getCurrent(), postPage.getSize(), postPage.getTotal());
        List<PostDTO> dtoList = convertToPostDTOList(postPage.getRecords());
        dtoPage.setRecords(dtoList);
        
        return dtoPage;
    }

    @Override
    public boolean publishPost(String title, String content, Integer categoryId, Long userId) {
        Post post = new Post();
        post.setTitle(title);
        post.setContent(content);
        post.setCategoryId(categoryId);
        post.setUserId(userId);
        post.setViewCount(0);
        post.setLikeCount(0);
        post.setCommentCount(0);
        post.setIsFeatured(0);
        
        return this.save(post);
    }

    @Override
    public PostDTO getPostDetail(Long id) {
        Post post = this.getById(id);
        if (post == null) {
            return null;
        }
        return convertToPostDTO(post);
    }

    @Override
    public boolean increaseViewCount(Long id) {
        Post post = this.getById(id);
        if (post == null) {
            return false;
        }
        post.setViewCount(post.getViewCount() + 1);
        return this.updateById(post);
    }

    @Override
    public boolean deletePost(Long id) {
        return this.removeById(id);
    }

    @Override
    public List<PostDTO> getHotPosts(int limit) {
        QueryWrapper<Post> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("like_count + comment_count");
        queryWrapper.last("LIMIT " + limit);
        List<Post> posts = this.list(queryWrapper);
        return convertToPostDTOList(posts);
    }

    @Override
    public Page<PostDTO> getUserPosts(Long userId, int page, int size) {
        Page<Post> pageParam = new Page<>(page, size);
        QueryWrapper<Post> queryWrapper = new QueryWrapper<>();
        
        // 筛选指定用户的帖子
        queryWrapper.eq("user_id", userId);
        
        // 按创建时间倒序排列
        queryWrapper.orderByDesc("create_time");
        
        Page<Post> postPage = this.page(pageParam, queryWrapper);
        
        // 转换为DTO并填充用户信息
        Page<PostDTO> dtoPage = new Page<>(postPage.getCurrent(), postPage.getSize(), postPage.getTotal());
        List<PostDTO> dtoList = convertToPostDTOList(postPage.getRecords());
        dtoPage.setRecords(dtoList);
        
        return dtoPage;
    }

    @Override
    public boolean setPostFeatured(Long postId, Integer isFeatured) {
        Post post = this.getById(postId);
        if (post == null) {
            return false;
        }
        post.setIsFeatured(isFeatured);
        return this.updateById(post);
    }

    @Override
    public Page<PostDTO> getFeaturedPosts(int page, int size) {
        Page<Post> pageParam = new Page<>(page, size);
        QueryWrapper<Post> queryWrapper = new QueryWrapper<>();
        
        // 筛选精华帖子
        queryWrapper.eq("is_featured", 1);
        
        // 按创建时间倒序排列
        queryWrapper.orderByDesc("create_time");
        
        Page<Post> postPage = this.page(pageParam, queryWrapper);
        
        // 转换为DTO并填充用户信息
        Page<PostDTO> dtoPage = new Page<>(postPage.getCurrent(), postPage.getSize(), postPage.getTotal());
        List<PostDTO> dtoList = convertToPostDTOList(postPage.getRecords());
        dtoPage.setRecords(dtoList);
        
        return dtoPage;
    }
    
    /**
     * 将Post列表转换为PostDTO列表，并填充用户信息
     */
    private List<PostDTO> convertToPostDTOList(List<Post> posts) {
        if (posts == null || posts.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 获取所有用户ID
        List<Long> userIds = posts.stream()
                .map(Post::getUserId)
                .distinct()
                .collect(Collectors.toList());
        
        // 批量查询用户信息
        Map<Long, User> userMap = userService.listByIds(userIds).stream()
                .collect(Collectors.toMap(User::getId, user -> user));
        
        // 转换为DTO并填充用户信息
        return posts.stream().map(post -> {
            PostDTO dto = new PostDTO();
            // 复制所有Post字段
            dto.setId(post.getId());
            dto.setTitle(post.getTitle());
            dto.setContent(post.getContent());
            dto.setUserId(post.getUserId());
            dto.setCategoryId(post.getCategoryId());
            dto.setViewCount(post.getViewCount());
            dto.setLikeCount(post.getLikeCount());
            dto.setCommentCount(post.getCommentCount());
            dto.setIsFeatured(post.getIsFeatured());
            dto.setCreateTime(post.getCreateTime());
            dto.setUpdateTime(post.getUpdateTime());
            
            // 填充用户信息
            User user = userMap.get(post.getUserId());
            if (user != null) {
                dto.setUsername(user.getUsername());
                dto.setNickname(user.getNickname());
                dto.setAvatar(user.getAvatar());
            }
            
            return dto;
        }).collect(Collectors.toList());
    }
    
    /**
     * 将单个Post转换为PostDTO，并填充用户信息
     */
    private PostDTO convertToPostDTO(Post post) {
        PostDTO dto = new PostDTO();
        // 复制所有Post字段
        dto.setId(post.getId());
        dto.setTitle(post.getTitle());
        dto.setContent(post.getContent());
        dto.setUserId(post.getUserId());
        dto.setCategoryId(post.getCategoryId());
        dto.setViewCount(post.getViewCount());
        dto.setLikeCount(post.getLikeCount());
        dto.setCommentCount(post.getCommentCount());
        dto.setIsFeatured(post.getIsFeatured());
        dto.setCreateTime(post.getCreateTime());
        dto.setUpdateTime(post.getUpdateTime());
        
        // 填充用户信息
        User user = userService.getById(post.getUserId());
        if (user != null) {
            dto.setUsername(user.getUsername());
            dto.setNickname(user.getNickname());
            dto.setAvatar(user.getAvatar());
        }
        
        return dto;
    }
}
